<template>
  <view class="chat-page">
    <!-- 顶部导航栏 - 固定在顶部 -->
    <view class="nav-bar">
      <view class="back-btn" @click="handleNavigateBack">
        <image class="back-icon" src="/static/icons/left.png"></image>
      </view>
      <text class="page-title">AI面试官</text>
    </view>

    <!-- 聊天内容区 -->
    <view class="chat-content">
      <!-- 聊天记录（含用户回答+对应评价） -->
      <view 
        class="message-item" 
        :class="{'my-message': item.send_role === 'me', 'ai-message': item.send_role === 'ai', 'feedback-message': item.type === 'feedback'}"
        v-for="(item, index) in chatList" 
        :key="index"
      >
        <!-- AI面试官问题 -->
        <view class="message-bubble ai-bubble" v-if="item.send_role === 'ai' && item.type !== 'feedback'">
          <text class="message-text">{{ item.chat_info }}</text>
          <text class="sender-tag">AI面试官</text>
        </view>
        <!-- 我的回答 -->
        <view class="message-bubble my-bubble" v-if="item.send_role === 'me'">
          <text class="message-text">{{ item.chat_info }}</text>
          <text class="sender-tag">我</text>
        </view>
        <!-- 上一条回答的评价（AI发送，标为"回答评价"类型） -->
        <view class="message-bubble feedback-bubble" v-if="item.send_role === 'ai' && item.type === 'feedback' && isCompleted">
          <text class="feedback-label-text">回答评价：</text>
          <text class="message-text">{{ item.chat_info }}</text>
          <text class="sender-tag">AI面试官</text>
        </view>
      </view>
      
      <!-- AI思考中气泡 -->
      <view class="message-item" v-if="isAIThinking">
        <view class="message-bubble ai-thinking-bubble">
          <text class="thinking-text">AI正在思考</text>
          <view class="thinking-dots">
            <text class="dot">.</text>
            <text class="dot">.</text>
            <text class="dot">.</text>
          </view>
          <text class="sender-tag">AI面试官</text>
        </view>
      </view>
      
      <!-- 面试结束：显示总体评价 -->
      <view class="feedback-section" v-if="isCompleted">
        <text class="feedback-title">面试总结</text>
        <!-- 总体评价 -->
        <view class="feedback-content">
          <text class="feedback-label">总体评价：</text>
          <text class="feedback-text">{{ overallFeedback || '暂无总体评价' }}</text>
        </view>
        <!-- 历史回答评价汇总 -->
        <view class="feedback-content" v-if="feedbackList.length > 0">
          <text class="feedback-label">历史回答评价：</text>
          <view class="history-feedback-list">
            <view class="history-feedback-item" v-for="(fb, idx) in feedbackList" :key="idx">
              <text class="history-feedback-text">• {{ fb }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 输入栏 - 固定在底部，面试结束后隐藏 -->
    <view class="input-bar" v-if="!isCompleted">
      <input 
        class="input-box" 
        type="text" 
        placeholder="请输入你的回答" 
        v-model="inputValue"
      />
      <view class="send-btn" @click="tiJiaoHuiDa">
        <image class="send-icon" src="/static/icons/send.png"></image>
        <text class="send-text">发送</text>
      </view>
    </view>
  </view>
</template>

<script>
import { start, submitAnswer, end } from '@/api/interview.js'
export default {
  data() {
    return {
      sessionId: null,
      mockId: null,
      userId: null,
      job: null,
      inputValue: '',
      chatList: [], // 聊天记录
      initialQuestion: '', // 初始问题
      isCompleted: false,  // 面试是否结束
      feedbackList: [],    // 存储所有单条回答评价
      overallFeedback: '', // 面试总体评价
      isAIThinking: false  // 新增：AI是否正在思考
    }
  },
  onLoad(val) {
    this.userId = val.userId;
    this.job = val.job;
    this.open();
  },
  
  // 页面卸载时强制结束面试
  onUnload() {
    this.EndChat();
  },
  
  methods: {
    // 初始化面试：获取初始问题
    open() {
		this.isAIThinking = true;
      start({ userId: this.userId, job: this.job }).then(res => {
        if (res.code === 200) {
          this.sessionId = res.data.sessionId;
          this.mockId = res.data.mockId;
          this.isCompleted = res.data.isCompleted;
          this.initialQuestion = res.data.question;
          this.isAIThinking = false;
          // 初始问题加入聊天记录
          this.chatList.push({
            send_role: 'ai',
            chat_info: res.data.question,
            type: 'question'
          });
        }
      });
    },
    
    // 提交回答：触发AI评价+下一题（或结束）
    tiJiaoHuiDa() {
      const userAnswer = this.inputValue.trim();
      if (!userAnswer) return;

      // 1. 先将用户回答加入聊天记录
      this.chatList.push({
        send_role: 'me',
        chat_info: userAnswer,
        type: 'answer'
      });
      this.inputValue = ''; // 清空输入框

      // 2. 显示AI思考中状态
      this.isAIThinking = true;
      this.scrollToBottom();

      // 3. 调用接口提交回答
      submitAnswer({
        sessionId: this.sessionId,
        answer: userAnswer,
        userId: this.userId,
        mockId: this.mockId
      }).then(res => {
        // 4. 隐藏思考状态
        this.isAIThinking = false;
        
        if (res.code === 200) {
          const { isCompleted, feedback, question, overallFeedback } = res.data;
          this.isCompleted = isCompleted;
          this.overallFeedback = overallFeedback || this.overallFeedback;

          // 5. 若有单条回答评价，加入聊天记录
          if (feedback) {
            this.chatList.push({
              send_role: 'ai',
              chat_info: feedback,
              type: 'feedback'
            });
            this.feedbackList.push(feedback);
          }

          // 6. 若面试未结束且有下一题，加入聊天记录
          if (!isCompleted && question) {
            this.chatList.push({
              send_role: 'ai',
              chat_info: question,
              type: 'question'
            });
          }

          // 7. 滚动到最新消息
          this.scrollToBottom();
        }
      }).catch(() => {
        this.isAIThinking = false; // 出错时也隐藏思考状态
      });
    },
    
    // 结束面试（调用接口）
    EndChat() {
      if (this.sessionId) {
        end({ sessionId: this.sessionId }).then(res => {
          console.log('面试正常结束', res);
        }).catch(err => {
          console.error('结束面试接口调用失败', err);
        });
      }
    },
    
    // 处理返回按钮：先结束面试再返回
    handleNavigateBack() {
      this.EndChat();
      uni.navigateBack();
    },
    
    // 滚动到聊天底部
    scrollToBottom() {
      setTimeout(() => {
        const query = uni.createSelectorQuery().in(this);
        query.select('.chat-content').boundingClientRect(rect => {
          if (rect) {
            uni.pageScrollTo({
              scrollTop: rect.scrollHeight,
              duration: 0
            });
          }
        }).exec();
      }, 100);
    }
  }
}
</script>

<style scoped>
/* 页面基础样式 */
.chat-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 顶部导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  height: 44px;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  padding: 0 15px;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
}
.back-btn {
  width: 20px;
  height: 20px;
}
.back-icon {
  width: 100%;
  height: 100%;
}
.page-title {
  flex: 1;
  text-align: center;
  font-size: 17px;
  font-weight: bold;
  color: #333;
}

/* 聊天内容区 */
.chat-content {
  flex: 1;
  padding: 15px;
  padding-top: 60px;
  padding-bottom: 70px;
  overflow-y: scroll;
  box-sizing: border-box;
}
.message-item {
  margin-bottom: 18px;
}

/* 消息气泡通用样式 */
.message-bubble {
  max-width: 65%;
  padding: 12px 15px;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  position: relative;
  box-sizing: border-box;
}
.message-text {
  font-size: 14px;
  line-height: 1.5;
  color: #333;
}
.sender-tag {
  font-size: 10px;
  color: #999;
  position: absolute;
  top: -18px;
}

/* 我的回答（居右） */
.my-bubble {
  background-color: #d3eafd;
  margin-left: auto;
}
.my-bubble .sender-tag {
  right: 0;
}

/* AI问题（居左） */
.ai-bubble {
  background-color: #ffffff;
  border: 1px solid #eee;
  margin-right: auto;
}
.ai-bubble .sender-tag {
  left: 0;
}

/* 回答评价（居左，特殊样式） */
.feedback-bubble {
  background-color: #fff8e6;
  border: 1px solid #ffe082;
  margin-right: auto;
}
.feedback-label-text {
  font-size: 12px;
  color: #ff8f00;
  font-weight: 500;
  margin-bottom: 4px;
  display: inline-block;
}

/* AI思考中气泡 */
.ai-thinking-bubble {
  background-color: #f5f5f5;
  border: 1px dashed #ddd;
  margin-right: auto;
  min-width: 120px;
}
.thinking-text {
  font-size: 14px;
  color: #666;
  display: inline-block;
}
.thinking-dots {
  display: inline-flex;
}
.dot {
  font-size: 24px;
  color: #666;
  animation: blink 1.4s infinite both;
}
.dot:nth-child(2) {
  animation-delay: 0.2s;
}
.dot:nth-child(3) {
  animation-delay: 0.4s;
}
@keyframes blink {
  0%, 100% { opacity: 0.2; }
  50% { opacity: 1; }
}

/* 底部输入栏 */
.input-bar {
  display: flex;
  align-items: center;
  background-color: #fff;
  border-top: 1px solid #eee;
  padding: 10px 15px;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 100;
  box-sizing: border-box;
}
.input-box {
  flex: 1;
  height: 40px;
  line-height: 40px;
  background-color: #f8f8f8;
  border-radius: 20px;
  padding: 0 18px;
  margin-right: 12px;
  font-size: 14px;
  border: none;
  outline: none;
}
.send-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #409eff;
  color: #fff;
  border-radius: 20px;
  padding: 0 18px;
  height: 40px;
  line-height: 40px;
}
.send-icon {
  width: 18px;
  height: 18px;
  margin-right: 6px;
}
.send-text {
  font-size: 14px;
  font-weight: 500;
}

/* 面试结束总结区域 */
.feedback-section {
  background-color: #fff;
  border-radius: 10px;
  padding: 18px;
  margin-top: 20px;
  border: 1px solid #eee;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
.feedback-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
  display: block;
  padding-bottom: 8px;
  border-bottom: 1px solid #f5f5f5;
}
.feedback-content {
  margin-bottom: 12px;
}
.feedback-label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
  display: block;
  margin-bottom: 6px;
}
.feedback-text {
  font-size: 14px;
  color: #333;
  line-height: 1.6;
}
.history-feedback-list {
  padding-left: 12px;
}
.history-feedback-item {
  margin-bottom: 8px;
}
.history-feedback-text {
  font-size: 14px;
  color: #333;
  line-height: 1.5;
}
</style>